<!doctype html>
<title>WebVTT parser tests</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<div id=log></div>
<script>
setup({explicit_done: true});
var files = [];
var path = 'support/';
var cueDefaults = {
"id":"",
"startTime":0,
"endTime":1,
"pauseOnExit":false,
//"vertical":"", (not supported)
"snapToLines":true,
"line":-1,
"position":50,
"size":100,
"align":"middle"
}
var cueCounts;
(function(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', path+'cue-counts.json', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            cueCounts = JSON.parse(xhr.responseText);
            for (var file in cueCounts) {
                files.push(file);
            }
            startTests();
        }
    }
    xhr.send();
})();

function checkProps(cue, exp, i) {
    for (var prop in cueDefaults) {
        if (!(prop in exp))
            exp[prop] = cueDefaults[prop];
        assert_equals(cue[prop], exp[prop], prop + ' (cue '+(i+1)+')');
    }
}

function startTests() {
    files.forEach(function(file) {
        var t = async_test(document.title+', '+file);
        t.step(function(){
            var video = document.createElement('video');
            var track = document.createElement('track');
            assert_true('src' in track, 'track element not supported');
            track.src = path + file;
            track['default'] = true;
            track.kind = 'subtitles';
            track.onload = this.step_func(trackLoaded);
            track.onerror = this.step_func(trackError);
            video.appendChild(track);
            document.body.appendChild(video);
        });
    });
    done();
}

function trackLoaded(e) {
    var track = e.target;
    var video = track.parentNode;
    setTimeout(removeElm, 0, video);
    var cues = video.textTracks[0].cues;
    var file = track.src.substr(track.src.lastIndexOf('/') + 1);
    assert_equals(cues.length, cueCounts[file], 'number of cues');
    var expected;
    var cue;
    for (var i = 0; i < cues.length; ++i) {
        cue = cues[i];
        expected = JSON.parse(cue.text);
        assert_not_equals(expected, 'FAIL', 'cue '+(i+1)+' should have been dropped');
        checkProps(cue, expected, i);
    }
    this.done();
}

function trackError(e) {
    var track = e.target;
    var video = track.parentNode;
    setTimeout(removeElm, 0, video);
    var file = track.src.substr(track.src.lastIndexOf('/') + 1);
    assert_equals('error', cueCounts[file], 'got unexpected error event');
    this.done();
}

function removeElm(elm) {
    document.body.removeChild(elm);
}

</script>
